/**  
* <p>Title: DataSourceConfiguration</p>  
* <p>Description: </p>  
* @author 王敞   365799712@qq.com
* @date 2020年7月15日  

*/  
package com.woniuxy.profile.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**  
* <p>Title: DataSourceConfiguration</p>  
* <p>Description: </p>  
* @author 王敞   365799712@qq.com
* @date 2020年7月15日  
*/
public class DataSourceConfiguration {
	//@configurationProperties该注解用于创建完对象后，
		//即将加入ioc容器是自动通过prefix到application.yml
		//文件中找到指定的配置信息，再将配置信息赋值给刚才创建bean
		@Bean
		@ConfigurationProperties(prefix = "spring.datasource")
		public  DataSource druidDataSource() {
			DruidDataSource druiDataSource = new DruidDataSource();
			return druiDataSource;
		}
		
		//设置druid的代理
		@Bean("dataSource")//指定名字为dataSource
		@Primary //优先使用，bean名字、类型相同时
		public DataSourceProxy dataSourceProxy(DataSource druidDataSource) {
			return new DataSourceProxy(druidDataSource);
		}
		
		//设置SQLsessionfactory
		@Bean
		public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy) throws Exception {
			SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
			//设置数据源
			sqlSessionFactoryBean.setDataSource(dataSourceProxy);
			//加载mapper.xml
			sqlSessionFactoryBean.setMapperLocations(
					new PathMatchingResourcePatternResolver()
					.getResources("classpath:/mapper/*.xml"));
			//设置事务工厂，用于创建事务
			sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
			//
			return sqlSessionFactoryBean.getObject();
			
		}
}
